package com.lh.auth.conf;


import com.lh.auth.utils.RsaUtils;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;


/**
 * @author liuhe
 * @date 2020/07/07
 */
@Data
@Slf4j
@ConfigurationProperties(prefix = "leyi.jwt")
public class JwtProperties {
    private String secret;
    private String publicKeyPath;
    private String privateKeyPath;
    private int expire;
    private String cookieName;
    private int cookieMaxAge; // cookie过期时间

    private PublicKey publicKey; // 公钥
    private PrivateKey privateKey; // 私钥

    /**
     * @PostContruct：在构造方法执行之后执行该方法
     */
    @PostConstruct
    public void init() {
        try {
            File pubKey = new File(publicKeyPath);
            File priKey = new File(privateKeyPath);
            if (!pubKey.exists() || !priKey.exists()) {
                // 生成公钥和私钥
                RsaUtils.generateKey(publicKeyPath, privateKeyPath, secret);
            }
            // 获取公钥和私钥
            this.publicKey = RsaUtils.getPublicKey(publicKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(privateKeyPath);
        } catch (Exception e) {
            log.error("初始化公钥和私钥失败！", e);
            throw new RuntimeException();
        }
    }
}

